package com.faintlight.service.impl;

import com.faintlight.dto.CapsuleDTO;
import com.faintlight.exception.WarmException;
import com.faintlight.model.Capsule;
import com.faintlight.repository.CapsuleRepository;
import com.faintlight.service.CapsuleService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CapsuleServiceImpl implements CapsuleService {

    private static final Logger logger = LoggerFactory.getLogger(CapsuleServiceImpl.class);

    private final CapsuleRepository capsuleRepository;

    @Override
    @Transactional
    public Capsule createCapsule(Capsule capsule) {
        logger.info("📥 创建胶囊: 标题={}, 解锁时间={}", capsule.getTitle(), capsule.getUnlockTime());
        if (capsule.getUnlockTime().isBefore(LocalDateTime.now().plusDays(1))) {
            throw new WarmException("解锁时间至少为明天");
        }
        capsule.setTemperature(28);
        Capsule saved = capsuleRepository.save(capsule);
        return saved;
    }

    @Override
    @Transactional
    public Capsule unlockCapsule(Long capsuleId) {
        return capsuleRepository.findById(capsuleId)
                .map(capsule -> {
                    if (capsule.getStatus() != Capsule.Status.LOCKED) throw new WarmException("胶囊已解锁或无效状态");
                    capsule.setStatus(Capsule.Status.UNLOCKED);
                    Capsule unlocked = capsuleRepository.save(capsule);
                    return unlocked;
                })
                .orElseThrow(() -> new WarmException("未找到指定胶囊"));
    }

    @Override
    public List<CapsuleDTO> getUserCapsules(Long userId) {
        List<Capsule> capsules = capsuleRepository.findByCreatedBy_IdAndStatus(userId, Capsule.Status.LOCKED);
        return capsules.stream()
                .map(CapsuleDTO::fromEntity)
                .collect(Collectors.toList());
    }



    @Override
    public void processUnlockTasks() {
        List<Capsule> capsules = capsuleRepository.findLockCapsulesBefore(LocalDateTime.now());
        capsules.forEach(capsule -> {
            capsule.setStatus(Capsule.Status.UNLOCKED);
            capsuleRepository.save(capsule);
        });
    }

    @Override
    public Capsule getCapsuleById(Long id) {
        return capsuleRepository.findById(id).orElse(null);
    }

    @Override
    public Long getUserCapsuleCount(Long userId) {
        return capsuleRepository.countByCreatedBy_Id(userId);
    }
    @Override
    public List<CapsuleDTO> getUserCapsulesAllStatus(Long userId) {
        List<Capsule> capsules = capsuleRepository.findByCreatedBy_IdOrderByCreatedAtDesc(userId);
        return capsules.stream().map(CapsuleDTO::fromEntity).collect(Collectors.toList());
    }
}
